package com.koron.order.perambulate.controller;

import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.EasyExcelUtils;
import com.koron.order.perambulate.bean.excel.*;
import com.koron.order.perambulate.bean.query.CheckQuery;
import com.koron.order.perambulate.bean.query.LinePeramQuery;
import com.koron.order.perambulate.bean.query.PeramOrderQuery;
import com.koron.order.perambulate.bean.vo.LineMonitorVo;
import com.koron.order.perambulate.bean.vo.LinePerambulateVo;
import com.koron.order.perambulate.bean.vo.PerambulateOrderVo;
import com.koron.order.perambulate.service.LinePerambulateService;
import com.koron.order.risk.base.excel.ErrorFillRowWriteHandler;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName: LinePerambulateController
 * @Description:
 * @Date: 2023/1/31
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
//@RestController
//@RequestMapping("perambulate")
//@Api(tags = "线路巡视-卫星巡视")
public class LinePerambulateController {
    @Autowired
    private LinePerambulateService linePerambulateService;
    @Autowired
    private LinePerambulateConvertor linePerambulateConvertor;

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询卫星监测列表")
    public Response list(@RequestBody LinePeramQuery linePeramQuery  ){
        List list = ADOConnection.runTask(getCurrDs(), linePerambulateService, "list",List.class,linePeramQuery);
        return  Response.ok( "查询成功！",new PageInfo<>(list));
    }
    @GetMapping("/getDetailById")
    @ApiOperation("根据id查询卫星监测项详情")
    public Response getDetailById(@RequestParam("id") String id){
        LinePeramQuery LinePeramDetail = ADOConnection.runTask(getCurrDs(), linePerambulateService, "getLinePeramDetailById", LinePeramQuery.class, id);
    return Response.ok(LinePeramDetail);
    }

    @PostMapping("/InsertSinglePerm")
    @ApiOperation("新增一条卫星巡视风险管理")
    public Response<Integer> InsertSinglePerm( @RequestBody LinePerambulateVo linePerambulateVo){
        linePerambulateVo.setId(CodeTools.getCode32());
        linePerambulateVo.setCreateName(getCurrUser().getCreateByName());
        Integer result = ADOConnection.runTask(getCurrDs(), linePerambulateService, "InsertSinglePerm", Integer.class, linePerambulateVo);
        return Response.ok("新增",result);
    }
    @PostMapping("/getPeramList")
    @ApiOperation("查询卫星巡视单记录")
    public Response getPeramList(@RequestBody PeramOrderQuery peramOrderQuery){
        List getPeramList = ADOConnection.runTask(getCurrDs(), linePerambulateService, "getPeramList", List.class, peramOrderQuery);
        return Response.ok(new PageInfo<>(getPeramList));
    }
    @PostMapping("/monitorList")
    @ApiOperation("查询卫星巡视变化管理详情")
    public Response<PageInfo> monitorList(@RequestBody CheckQuery checkQuery){
        List monitorList = ADOConnection.runTask(getCurrDs(), linePerambulateService, "monitorList", List.class, checkQuery);
        return Response.ok("查询成功",new PageInfo<>(monitorList));
    }

    @GetMapping("/getMonitorById")
    @ApiOperation("查询卫星监测变化详情")
    public Response<LineMonitorVo> getMonitorById(@RequestParam String  id){
        LineMonitorVo monitorVo = ADOConnection.runTask(getCurrDs(), linePerambulateService, "getMonitorDetailById", LineMonitorVo.class, id);
        return  Response.ok(monitorVo);

    }

    @PostMapping("/insert")
    @ApiOperation("新增监测变化管理")
    public Response insert (@RequestBody PerambulateOrderVo perambulateOrderVo){
        perambulateOrderVo.setPeramName(getCurrUser().getName());
        perambulateOrderVo.setId(CodeTools.getCode32());
      Integer  insert = ADOConnection.runTask(getCurrDs(), linePerambulateService, "insert", Integer.class,perambulateOrderVo);
        if(insert >0 ){
            return Response.ok();
        }
        return Response.fail();
    }

    @SneakyThrows
    @ApiOperation(value = "下载卫星巡视模板")
    @GetMapping("/template1")
    public void template1(HttpServletResponse response) {
        String path = "excel/line_perambulate_import.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("卫星巡视风险导入单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());

    }
    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("/importPerambulate")
    public Response importFile1(@RequestParam("file")MultipartFile file){
        PerambulateStringStringConverter stringConvetor = new PerambulateStringStringConverter();
        PerambulateExcelListener listener = new PerambulateExcelListener(linePerambulateService);
         EasyExcel.read(file.getInputStream(), LinePerambulateExcel.class, listener)
                .registerConverter(stringConvetor)
                .headRowNumber(1)
                .sheet(0)
                .doRead();
        if (listener.getExcelErrors().size() != 0) {
            String path = "excel/linePeram_import_error.xlsx";
            ClassPathResource classPathResource = new ClassPathResource(path);
            // 输出错误文件
            String filename = CodeTools.getCodeNo("LinePerambulateFile", 3);
            String tempPath = EasyExcelUtils.createTempFile(filename, "xlsx");
            log.warn("导入失败，错误文件在：{}", tempPath);
            EasyExcel.write(tempPath)
                    .withTemplate(classPathResource.getInputStream())
                    .head(LinePerambulateExcel.class)
                    .needHead(false)
                    .registerConverter(stringConvetor)
                    .registerWriteHandler(new ErrorFillRowWriteHandler(listener.getExcelErrors()))
                    .sheet(0)
                    .doWrite(listener.getErrorRisk());
            return Response.ok("temp/" + filename + ".xlsx");
        }
        return Response.ok("导入成功", null);
    }



    @SneakyThrows
    @ApiOperation(value = "下载卫星监视模板")
    @GetMapping("/template2")
    public void template2(HttpServletResponse response) {
        String path = "excel/import_monitor.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("卫星监视变化导入单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());

    }


    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("/importMonitor")
    public Response importFile2(@RequestParam("file")MultipartFile file , @RequestParam("peramId") String peramId){
        MonitorStringConverter monitorStringConverter = new MonitorStringConverter();
        MonitorListener monitorListener = new MonitorListener(linePerambulateService,peramId);
        EasyExcel.read(file.getInputStream(), MonitorChangeExcel.class, monitorListener)
                .registerConverter(monitorStringConverter)
                .headRowNumber(1)
                .sheet(0)
                .doRead();
        if (monitorListener.getExcelErrors().size() != 0) {
            String path = "excel/import_monitor_error.xlsx";
            ClassPathResource classPathResource = new ClassPathResource(path);
            // 输出错误文件
            String filename = CodeTools.getCodeNo("MonitorFile", 3);
            String tempPath = EasyExcelUtils.createTempFile(filename, "xlsx");
            log.warn("导入失败，错误文件在：{}", tempPath);
            EasyExcel.write(tempPath)
                    .withTemplate(classPathResource.getInputStream())
                    .head(MonitorChangeExcel.class)
                    .needHead(false)
                    .registerConverter(monitorStringConverter)
                    .registerWriteHandler(new ErrorFillRowWriteHandler(monitorListener.getExcelErrors()))
                    .sheet(0)
                    .doWrite(monitorListener.getErrorRisk());
            return Response.ok("temp/" + filename + ".xlsx");
        }
        return Response.ok("导入成功", null);
    }
}
